package com.ruoyi.behavior.service.impl;

import com.ruoyi.behavior.domain.Replies;
import com.ruoyi.behavior.domain.VerReviewImage;
import com.ruoyi.behavior.domain.dto.*;
import com.ruoyi.behavior.domain.dto.filter.FilterDto;
import com.ruoyi.behavior.domain.dto.filter.SkuFilterDto;
import com.ruoyi.behavior.domain.dto.filter.SupFilterDto;
import com.ruoyi.behavior.domain.vo.*;
import com.ruoyi.behavior.mapper.VerReviewMapper;
import com.ruoyi.behavior.service.IVerReviewService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SpecGroupUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户行为Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-10
 */
@Service
public class VerReviewServiceImpl implements IVerReviewService {
    @Autowired
    private VerReviewMapper verReviewMapper;

    /**
     * 根据分类ID获取评论
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<CategoryReviewDto> getReviewByCategoryId(Long categoryId) {
        List<CategoryReviewDto> categoryReviewDto = verReviewMapper.getReviewByCategoryId(categoryId);
        // 处理urls - 将相同skuId的URL封装进urls[]
        return processUrlsBySkuId(categoryReviewDto);
    }

    /**
     * 分页
     *
     * @param categoryReviewDto
     * @return
     */
    @Override
    public List<CategoryReviewDto> pageList(CategoryReviewDto categoryReviewDto) {
        List<CategoryReviewDto> list = verReviewMapper.pageList(categoryReviewDto);

        // 处理urls - 将相同skuId的URL封装进urls[]
        return processUrlsBySkuId(list);
    }

    /**
     * 根据skuId获取sku信息
     *
     * @param skuId
     * @return
     */
    @Override
    public SkuReviewDto getSkuInfo(Long skuId) {
        List<SkuReviewDto> skuReviewDtoList = verReviewMapper.getSkuInfo(skuId);
        return processSkuUrls(skuReviewDtoList);
    }

    /**
     * 处理URLs - 将相同skuId的URL封装进urls[]
     *
     * @param list 原始数据列表
     * @return 处理后的数据列表
     */
    private List<CategoryReviewDto> processUrlsBySkuId(List<CategoryReviewDto> list) {
        if (list == null || list.isEmpty()) {
            return list;
        }

        // 按skuId分组，收集每个SKU的所有URL，过滤掉skuId为null的记录
        Map<Long, List<CategoryReviewDto>> groupedBySkuId = list.stream().filter(item -> item.getSkuId() != null)
                .collect(Collectors.groupingBy(CategoryReviewDto::getSkuId));

        List<CategoryReviewDto> result = new ArrayList<>();

        for (Map.Entry<Long, List<CategoryReviewDto>> entry : groupedBySkuId.entrySet()) {
            List<CategoryReviewDto> skuItems = entry.getValue();
            if (!skuItems.isEmpty()) {
                // 取第一个作为基础对象
                CategoryReviewDto baseItem = skuItems.get(0);

                // 收集所有URL
                List<String> urls = new ArrayList<>();
                for (CategoryReviewDto item : skuItems) {
                    if (item.getUrl() != null && !item.getUrl().trim().isEmpty()) {
                        urls.add(item.getUrl());
                    }
                }

                // 设置URLs列表
                baseItem.setUrls(urls);

                // 获取并设置回复列表
                if (baseItem.getReviewId() != null) {
                    List<RepliesVo> replies = verReviewMapper.getReplies(baseItem.getReviewId());
                    baseItem.setReplies(replies != null ? replies : new ArrayList<>());
                } else {
                    baseItem.setReplies(new ArrayList<>());
                }

                result.add(baseItem);
            }
        }

        return result;
    }

    /**
     * 处理SKU URLs - 将相同skuId的URL封装进urls[]
     *
     * @param list 原始数据列表
     * @return 处理后的SKU对象
     */
    private SkuReviewDto processSkuUrls(List<SkuReviewDto> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }

        // 取第一个作为基础对象
        SkuReviewDto baseItem = list.get(0);

        // 收集所有URL
        List<String> urls = new ArrayList<>();
        for (SkuReviewDto item : list) {
            if (item.getUrl() != null && !item.getUrl().trim().isEmpty()) {
                urls.add(item.getUrl());
            }
        }

        // 设置URLs列表
        baseItem.setUrls(urls);

        return baseItem;
    }

    /**
     * 新增
     *
     * @param verReviewVo
     * @return
     */
    @Override
    @Transactional
    public int add(VerReviewVo verReviewVo) {
        // 1. 插入ver_review表
        Long maxId = verReviewMapper.getMaxId();
        verReviewVo.setId(maxId == null ? 1L : maxId + 1);
        verReviewVo.setCreateTime(DateUtils.getNowDate());
        int result = verReviewMapper.add(verReviewVo);

        // 2. 插入ver_review_image表（如果有图片URL）
        if (result > 0 && verReviewVo.getUrls() != null && !verReviewVo.getUrls().isEmpty()) {
            Long maxImageId = verReviewMapper.getMaxImageId();
            Long currentImageId = maxImageId == null ? 1L : maxImageId + 1;

            for (String url : verReviewVo.getUrls()) {
                if (url != null && !url.trim().isEmpty()) {
                    VerReviewImage reviewImage = new VerReviewImage();
                    reviewImage.setId(currentImageId++);
                    reviewImage.setReviewId(verReviewVo.getId());
                    reviewImage.setUrl(url);
                    verReviewMapper.addReviewImage(reviewImage);
                }
            }
        }

        return result;
    }

    /**
     * 根据sku_id获取统计信息与评论列表
     *
     * @param request
     * @return
     */
    @Override
    public SkuReviewListDto getSkuReviewList(SkuIdRequestDto request) {
        Long skuId = request.getSkuId();
        SkuFilterDto filter = request.getFilter();

        // 设置默认值
        if (filter == null) {
            filter = new SkuFilterDto();
        }
        if (filter.getPageNum() == null) {
            filter.setPageNum(1);
        }
        if (filter.getSize() == null) {
            filter.setSize(20);
        }
        if (filter.getSort() == null) {
            filter.setSort(0); // 默认按评分排序
        }
        if (filter.getWithPhotos() == null) {
            filter.setWithPhotos(0); // 默认返回全部
        }
        if (filter.getRate() == null) {
            filter.setRate(0); // 默认返回全部评分
        }
        // 计算偏移量
        filter.setOffset((filter.getPageNum() - 1) * filter.getSize());

        // 获取评论列表
        List<SkuReviewListDto> reviewList = verReviewMapper.getSkuReviewList(skuId, filter);
        // 获取评分统计
        List<AmountOfRateVo> rateStatistics = verReviewMapper.getRateStatistics(skuId);
        // 获取评论图片URLs
        List<Map<String, Object>> urlList = verReviewMapper.getUrls(skuId);

        if (reviewList == null || reviewList.isEmpty()) {
            return null;
        }

        Map<Long, List<String>> urlMap = new HashMap<>();
        for (Map<String, Object> urlItem : urlList) {
            Long reviewId = (Long) urlItem.get("id");
            String urlString = (String) urlItem.get("urls");

            // 处理urls
            if (reviewId != null) {
                List<String> urls = new ArrayList<>();
                if (urlString != null && !urlString.isEmpty()) {
                    String[] urlArray = urlString.split(",");
                    for (String url : urlArray) {
                        if (url != null && !url.trim().isEmpty()) {
                            urls.add(url.trim());
                        }
                    }
                }
                urlMap.put(reviewId, urls);
            }
        }

        // 主返回
        SkuReviewListDto dto = new SkuReviewListDto();
        if (!reviewList.isEmpty()) {
            dto.setTotal(reviewList.get(0).getTotal());
            dto.setAvg(reviewList.get(0).getAvg());
        }
        // 处理amountOfRate
        dto.setAmountOfRate(rateStatistics);

        // 处理ReviewList
        List<ReviewListVo> reviewVoList = new ArrayList<>();
        for (SkuReviewListDto item : reviewList) {
            ReviewListVo reviewVo = new ReviewListVo();
            reviewVo.setId(item.getId());
            reviewVo.setUserName(item.getUserName());
            reviewVo.setAvator(item.getAvator());
            reviewVo.setRate(item.getRate());
            reviewVo.setTitle(item.getTitle());
            reviewVo.setDescription(item.getDescription());
            reviewVo.setLike(item.getLikes());
            reviewVo.setReplies(new ArrayList<>());
            reviewVo.setReplies(verReviewMapper.getReplies(item.getId()));

            // 设置URLs
            List<String> urls = urlMap.get(item.getId());
            reviewVo.setUrls(urls != null ? urls : new ArrayList<>());

            reviewVoList.add(reviewVo);
        }

        dto.setReviewList(reviewVoList);

        return dto;
    }

    /**
     * 根据spu_id获取统计信息与评论列表
     *
     * @param
     * @return
     */
    @Override
    public List<SpuReviewDto> getSpuReviewList(SupIdRequestDto request) {
        Long spuId = request.getSpuId();
        SupFilterDto filter = request.getFilter();

        // 设置默认值
        if (filter == null) {
            filter = new SupFilterDto();
        }
        if (filter.getPageNum() == null) {
            filter.setPageNum(1);
        }
        if (filter.getSize() == null) {
            filter.setSize(20);
        }
        if (filter.getSort() == null) {
            filter.setSort(0); // 默认按评分排序
        }
        if (filter.getWithPhotos() == null) {
            filter.setWithPhotos(0); // 默认返回全部
        }
        // 计算偏移量
        filter.setOffset((filter.getPageNum() - 1) * filter.getSize());

        // 获取主体评论列表
        List<SpuReviewDto> resultList = verReviewMapper.getSpuReviewList(spuId, filter);

        // 为每个评论填充详细信息
        for (SpuReviewDto review : resultList) {
            // 获取SKU信息
            if (review.getSkuId() != null) {
                List<SkuReviewDto> skuInfoList = verReviewMapper.getSkuInfo(review.getSkuId());
                if (skuInfoList != null && !skuInfoList.isEmpty()) {
                    review.setSkuInfo(skuInfoList.get(0)); // 取第一个SKU信息
                }
            }

            // 获取回复信息
            List<RepliesVo> replies = verReviewMapper.getReplies(review.getId());
            review.setReplies(replies);

            // 获取评论图片URLs
            List<Map<String, Object>> urlList = verReviewMapper.getUrlsByReviewId(review.getId());
            List<String> urls = new ArrayList<>();
            if (urlList != null) {
                for (Map<String, Object> urlItem : urlList) {
                    if (urlItem != null) {
                        String urlString = (String) urlItem.get("urls");
                        if (urlString != null && !urlString.isEmpty()) {
                            String[] urlArray = urlString.split(",");
                            for (String url : urlArray) {
                                if (url != null && !url.trim().isEmpty()) {
                                    urls.add(url.trim());
                                }
                            }
                        }
                    }
                }
            }
            review.setReviewUrls(urls);
        }

        return resultList;
    }

    /**
     * 根据用户id获取订单项和评论
     *
     * @param request 包含用户ID和筛选条件的请求对象
     * @return
     */
    @Override
    public List<ReviewResultDto> getOrderItemAndReview(GetOrderItemAndReviewRequestDto request) {
        Long userId = request.getUserId();
        FilterDto filter = request.getFilter();

        // 设置默认值
        if (filter == null) {
            filter = new FilterDto();
        }
        if (filter.getPageNum() == null) {
            filter.setPageNum(1);
        }
        if (filter.getSize() == null) {
            filter.setSize(10);
        }

        // 计算偏移量
        filter.setOffset((filter.getPageNum() - 1) * filter.getSize());

        List<UserReviewDto> resultList = verReviewMapper.getOrderItemAndReview(userId, filter);

        // 按 orderItemId 分组
        Map<Long, List<UserReviewDto>> groupedByOrderItem = resultList.stream()
                .collect(Collectors.groupingBy(UserReviewDto::getOrderItemId));

        List<ReviewResultDto> responseList = new ArrayList<>();

        for (Map.Entry<Long, List<UserReviewDto>> entry : groupedByOrderItem.entrySet()) {
            Long orderItemId = entry.getKey();
            List<UserReviewDto> orderItems = entry.getValue();

            if (orderItems.isEmpty()) {
                continue;
            }

            // 取第一个订单项作为基础信息（同一个订单项应该有相同的skuId和isReviewed）
            UserReviewDto baseItem = orderItems.get(0);

            // 创建 ReviewResultDto
            ReviewResultDto resultDto = new ReviewResultDto();
            resultDto.setOrderItemId(orderItemId);
            resultDto.setSkuId(baseItem.getSkuId());
            resultDto.setIsReviewed(baseItem.getIsReviewed());

            // 构建 skuInfo 对象（取第一个订单项的SKU信息）
            UserSkuVo skuInfo = new UserSkuVo();
            UserReviewDto firstItem = orderItems.get(0);
            skuInfo.setSkuId(firstItem.getSkuId());
            skuInfo.setCode(firstItem.getCode());
            skuInfo.setCategoryId(firstItem.getCategoryId());
            skuInfo.setSpecData(firstItem.getSpecData());
            skuInfo.setPrice(firstItem.getPrice());
            skuInfo.setOriginalPrice(firstItem.getOriginalPrice());
            skuInfo.setSkuName(firstItem.getSkuName());
            skuInfo.setSkuDescription(firstItem.getSkuDescription());
            skuInfo.setStock(firstItem.getStock());
            skuInfo.setLowStock(firstItem.getLowStock());
            skuInfo.setWeight(firstItem.getWeight());
            skuInfo.setVolume(firstItem.getVolume());
            skuInfo.setStatus(firstItem.getStatus());
            skuInfo.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(firstItem.getSpecNameGroupRaw()));
            skuInfo.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(firstItem.getSpecValueGroupRaw()));
            skuInfo.setCreatedAt(firstItem.getCreatedAt());
            skuInfo.setUpdatedAt(firstItem.getUpdatedAt());
            skuInfo.setUrl(firstItem.getUrl());
            skuInfo.setSkuUrls(new ArrayList<>());

            if (firstItem.getUrl() != null && !firstItem.getUrl().isEmpty()) {
                // 分割逗号分隔的URL字符串
                String[] urls = firstItem.getUrl().split(",");
                for (String url : urls) {
                    if (url != null && !url.trim().isEmpty()) {
                        skuInfo.getSkuUrls().add(url.trim());
                    }
                }
            }
            resultDto.setSkuInfo(skuInfo);

            // 获取用户的所有评论信息
            List<ReviewVo> reviewList = verReviewMapper.getReviewList(userId);
            List<ReviewVo> processedReviewList = new ArrayList<>();

            for (ReviewVo review : reviewList) {
                // 处理评论的URLs
                review.setUrls(new ArrayList<>());
                if (review.getUrlsRaw() != null && !review.getUrlsRaw().isEmpty()) {
                    String[] urls = review.getUrlsRaw().split(",");
                    for (String url : urls) {
                        if (url != null && !url.trim().isEmpty()) {
                            review.getUrls().add(url.trim());
                        }
                    }
                }

                // 获取该评论的所有回复
                List<RepliesVo> replies = verReviewMapper.getReplies(review.getId());
                review.setReplies(replies);
                processedReviewList.add(review);
            }
            resultDto.setReview(processedReviewList);

            responseList.add(resultDto);
        }

        return responseList;
    }

    /**
     * 修改
     *
     * @param verReviewVo
     * @return
     */
    @Override
    @Transactional
    public Object edit(VerReviewVo verReviewVo) {
        verReviewVo.setUpdateTime(new Date());
        int result = verReviewMapper.edit(verReviewVo);
        if (result > 0) {
            // 删除该评论的所有图片
            verReviewMapper.deleteReviewImage(verReviewVo.getId());
            // 添加新的图片
            if (verReviewVo.getUrls() != null && !verReviewVo.getUrls().isEmpty()) {
                for (String url : verReviewVo.getUrls()) {
                    VerReviewImage verReviewImage = new VerReviewImage();
                    verReviewImage.setReviewId(verReviewVo.getId());
                    verReviewImage.setUrl(url);
                    verReviewImage.setId(verReviewMapper.getMaxImageId() + 1L);
                    verReviewMapper.addReviewImage(verReviewImage);
                }
            }
            return "修改成功";
        }

        return result;
    }

    /**
     * 回复
     *
     * @param replies
     * @return
     */
    @Override
    public Replies reply(Replies replies) {
        Long replyToUserId = verReviewMapper.getReplyToUserId(replies.getReviewId());
        Long maxId = verReviewMapper.getMaxReplyId() + 1L;
        replies.setReplyToUserId(replyToUserId);
        replies.setId(maxId);
        replies.setIsDelete(0);
        replies.setCreatedTime(new Date());
        int result = verReviewMapper.reply(replies);
        if (result > 0) {
            return replies;
        } else {
            throw new RuntimeException("回复失败");
        }

    }
}
